<?php

namespace App\Http\Controllers\Admin;

use App\Helpers\ResponseData;
use App\Http\Controllers\Controller;
use App\Models\Admin;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
class RegisterController extends Controller
{
    use ResponseData;
    public function register(Request $request){
        //return $this->success($request->all());
        //password_confirmation
        $validated = $this->validator($request->input());
        if($validated->fails()){
            $errors = $validated->errors()->messages();
            $errors['code']=201;
            return $errors;
        }
        $this->create($request->input());
        return $this->success('添加成功',200);
    }
    //验证用户密码
    protected function validator(array $data){
        $rules = [
            'phone' => 'required|string|min:11|unique:admins|alpha_dash',
            'password' => 'required|string|min:6|confirmed',
        ];
        $messages = [
            'unique'=>':attribute 手机号码已经存在',
            'required'=>':attribute 为必填项',
            'min'=>':attribute 长度最少 :min ,不符合要求',
            'email'=>':attribute 格式错误',
            'confirmed'=>'两次密码输入不一致'
        ];
        return Validator::make($data,$rules,$messages);
    }
//    创建账号
    protected function create(array $data){
        return Admin::create([
            'phone' => $data['phone'],
            'password' => Hash::make($data['password']),
        ]);
    }
}
